<template>
    <div class="purchaser-dashboard">
      <el-card>
        <h2>采购员仪表盘</h2>
        <p>这里是采购员的仪表盘，展示一些统计数据和图表。</p>
      </el-card>
      <div class="dashboard-container">
        <!-- 统计卡片 -->
        <el-row :gutter="20" class="statistics-cards">
          <el-col :span="6">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header-with-icon">
                  <el-icon><ShoppingCart /></el-icon>
                  <span>本月采购订单</span>
                </div>
              </template>
              <div class="statistic-value">{{ statistics.monthlyOrders }}</div>
              <div class="statistic-label">较上月 {{ statistics.orderGrowth > 0 ? '+' : '' }}{{ statistics.orderGrowth }}%</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header-with-icon">
                  <el-icon><Money /></el-icon>
                  <span>本月采购金额</span>
                </div>
              </template>
              <div class="statistic-value">¥{{ statistics.monthlyAmount.toLocaleString() }}</div>
              <div class="statistic-label">较上月 {{ statistics.amountGrowth > 0 ? '+' : '' }}{{ statistics.amountGrowth }}%</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header-with-icon">
                  <el-icon><Warning /></el-icon>
                  <span>库存预警</span>
                </div>
              </template>
              <div class="statistic-value">{{ statistics.stockWarnings }}</div>
              <div class="statistic-label">需要补货的商品数</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header-with-icon">
                  <el-icon><Goods /></el-icon>
                  <span>供应商数量</span>
                </div>
              </template>
              <div class="statistic-value">{{ statistics.supplierCount }}</div>
              <div class="statistic-label">本月新增 {{ statistics.newSuppliers }}</div>
            </el-card>
          </el-col>
        </el-row>
  
        <!-- 仓库补货情况卡片 -->
        <el-card class="stock-warning-card">
          <template #header>
            <div class="card-header">
              <span>仓库补货情况</span>
              <el-select v-model="selectedWarehouse" placeholder="选择仓库" style="width: 200px">
                <el-option
                  v-for="warehouse in warehouses"
                  :key="warehouse.id"
                  :label="warehouse.name"
                  :value="warehouse.id"
                />
              </el-select>
            </div>
          </template>
          <el-table :data="filteredStockWarnings" style="width: 100%">
            <el-table-column prop="name" label="产品名称" />
            <el-table-column prop="currentStock" label="当前库存" />
            <el-table-column prop="minStock" label="最低库存" />
            <el-table-column prop="gap" label="库存缺口">
              <template #default="{ row }">
                <span :class="{ 'text-danger': row.gap > 0 }">
                  {{ row.gap > 0 ? `-${row.gap}` : '0' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
              <template #default="{ row }">
                <el-tag :type="getStockStatusType(row.status)">{{ row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="handleQuickPurchase(row)"
                  :disabled="row.gap <= 0"
                >
                  采购
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
  
        <!-- 采购趋势图 -->
        <el-card class="trend-chart-card">
          <template #header>
            <div class="card-header">
              <span>采购趋势</span>
              <el-radio-group v-model="chartTimeRange" size="small">
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="quarter">本季度</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container">
            <v-chart class="chart" :option="purchaseTrendOption" autoresize />
          </div>
        </el-card>
  
        <!-- 快速采购对话框 -->
        <el-dialog
          v-model="purchaseDialogVisible"
          title="快速采购"
          width="500px"
        >
          <el-form
            ref="purchaseForm"
            :model="purchaseForm"
            :rules="purchaseRules"
            label-width="100px"
          >
            <el-form-item label="产品名称">
              <span>{{ currentProduct?.name }}</span>
            </el-form-item>
            <el-form-item label="供应商">
              <span>{{ currentProduct?.supplier }}</span>
            </el-form-item>
            <el-form-item label="采购数量" prop="quantity">
              <el-input-number 
                v-model="purchaseForm.quantity" 
                :min="1" 
                :step="10"
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="预计到货" prop="expectedDate">
              <el-date-picker
                v-model="purchaseForm.expectedDate"
                type="date"
                placeholder="选择日期"
                :disabled-date="disabledDate"
              />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="purchaseForm.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="purchaseDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handlePurchaseSubmit">确认采购</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, computed, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import { use } from 'echarts/core'
  import { CanvasRenderer } from 'echarts/renderers'
  import { LineChart } from 'echarts/charts'
  import {
    GridComponent,
    TooltipComponent,
    LegendComponent,
    TitleComponent
  } from 'echarts/components'
  import VChart from 'vue-echarts'
  import {
    ShoppingCart,
    Money,
    Warning,
    Goods
  } from '@element-plus/icons-vue'
  
  use([
    CanvasRenderer,
    LineChart,
    GridComponent,
    TooltipComponent,
    LegendComponent,
    TitleComponent
  ])
  
  // 统计数据
  const statistics = ref({
    monthlyOrders: 156,
    orderGrowth: 12.5,
    monthlyAmount: 258600,
    amountGrowth: -5.2,
    stockWarnings: 8,
    supplierCount: 24,
    newSuppliers: 2
  })
  
  // 仓库数据
  const selectedWarehouse = ref('')
  const warehouses = [
    { id: 1, name: '北京仓库' },
    { id: 2, name: '上海仓库' },
    { id: 3, name: '广州仓库' }
  ]
  
  // 库存预警数据
  const stockWarnings = ref([
    { name: '红富士苹果', currentStock: 80, minStock: 100, gap: 20, status: '库存不足', supplier: '北京水果批发市场' },
    { name: '香蕉', currentStock: 70, minStock: 100, gap: 30, status: '库存不足', supplier: '广州水果批发市场' },
    { name: '新鲜生菜', currentStock: 30, minStock: 50, gap: 20, status: '库存不足', supplier: '上海蔬菜批发市场' }
  ])
  
  // 过滤后的库存预警
  const filteredStockWarnings = computed(() => {
    if (!selectedWarehouse.value) return stockWarnings.value
    return stockWarnings.value.filter(item => item.warehouse === selectedWarehouse.value)
  })
  
  // 采购趋势图配置
  const chartTimeRange = ref('month')
  const purchaseTrendOption = computed(() => ({
    title: {
      text: '采购金额趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
      type: 'value',
      name: '采购金额（元）'
    },
    series: [{
      data: [15000, 22000, 18000, 25000, 20000, 30000, 25000],
      type: 'line',
      smooth: true
    }]
  }))
  
  // 快速采购对话框
  const purchaseDialogVisible = ref(false)
  const currentProduct = ref(null)
  const purchaseForm = ref({
    quantity: 0,
    expectedDate: '',
    remark: ''
  })
  
  const purchaseRules = {
    quantity: [{ required: true, message: '请输入采购数量', trigger: 'blur' }],
    expectedDate: [{ required: true, message: '请选择预计到货日期', trigger: 'change' }]
  }
  
  // 获取库存状态类型
  const getStockStatusType = (status) => {
    const types = {
      '库存不足': 'danger',
      '正常': 'success',
      '超储': 'warning'
    }
    return types[status] || 'info'
  }
  
  // 处理快速采购
  const handleQuickPurchase = (row) => {
    currentProduct.value = row
    purchaseForm.value = {
      quantity: row.gap,
      expectedDate: '',
      remark: ''
    }
    purchaseDialogVisible.value = true
  }
  
  // 禁用过去的日期
  const disabledDate = (time) => {
    return time.getTime() < Date.now() - 8.64e7
  }
  
  // 提交采购订单
  const handlePurchaseSubmit = async () => {
    try {
      // TODO: 调用接口提交采购订单
      ElMessage.success('采购订单已创建')
      purchaseDialogVisible.value = false
    } catch (error) {
      console.error('创建采购订单失败:', error)
      ElMessage.error('创建采购订单失败')
    }
  }
  
  onMounted(() => {
    // TODO: 获取实际数据
  })
  </script>
  
  <style scoped>
  .purchaser-dashboard {
    padding: 24px;
  }
  .dashboard-container {
    padding: 20px;
  }
  
  .statistics-cards {
    margin-bottom: 20px;
  }
  
  .card-header-with-icon {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  
  .statistic-value {
    font-size: 24px;
    font-weight: bold;
    color: #303133;
    margin: 10px 0;
  }
  
  .statistic-label {
    font-size: 14px;
    color: #909399;
  }
  
  .stock-warning-card,
  .trend-chart-card {
    margin-bottom: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .text-danger {
    color: #f56c6c;
  }
  
  .chart-container {
    height: 400px;
  }
  
  .chart {
    height: 100%;
  }
  </style>
